<template>
    <div class="donation-records">
        <van-nav-bar title="公益募捐" left-text="返回" left-arrow @click-left="goBack" fixed />
        <!-- 标题 -->
        <div class="donation-records-title">
            <img :src="imageUrl + fundraisingProjects.fundraisingProjectsPhoto" width="100%" height="200rem" />
            <div class="title-info">
                <span class="title">{{ fundraisingProjects.fundraisingProjectsName }}</span>
                <van-tag :type="fundraisingProjects.fundraisingProjectsType === '教育助学' ? 'primary' : fundraisingProjects.fundraisingProjectsType === '扶危助困' ? 'danger' : fundraisingProjects.fundraisingProjectsType === '乡村振兴' ? 'warning' : 'success'">{{ fundraisingProjects.fundraisingProjectsType }}</van-tag>
                <div>{{ fundraisingProjects.fundraisingProjectsIntroduction }}</div>
                <div class="processing">
                    <div class="processing-top">
                        <div class="top-left">
                            已筹金额（元）
                            <div class="number">{{ fundraisingProjects.totalAmount }}</div>
                        </div>
                        <div class="top-right">
                            剩余时间
                            <van-count-down :time="time" format="DD天HH时mm分ss秒" />
                        </div>
                    </div>
                    <div style="margin-top: 20px;">
                        <van-progress :percentage="fundraisingProjects.totalAmount / fundraisingProjects.expectedFundraisingAmount * 100" />
                    </div>
                    <div style="align-self: flex-end;margin-top: 5px;">目标金额{{ fundraisingProjects.expectedFundraisingAmount }}元</div>
                </div>
            </div>
        </div>
        <!-- 内容 -->
        <div style="margin-top: 10px;">
            <van-tabs scrollspy sticky>
                <van-tab v-for="item in titles" :title="item" :key="item" style="margin-bottom: 10px;background-color: white;padding: 10px;">
                    <div style="display: flex;margin-bottom: 10px;">
                        <div style="background-color:#1989FA;color: #1989FA;">1</div>
                        <div style="font-weight: bold;margin-left: 10px;">{{ item }}</div>
                    </div>
                    <div v-if="item === '项目介绍'">
                        <p v-html="fundraisingProjects.fundraisingProjectsContent"></p>
                    </div>
                    <div v-if="item === '项目进展'">
                        <van-steps direction="vertical" :active="0">
                            <van-step v-for="processing in processings" :key="processing.donationProcessingId">
                                <div style="display: flex;">
                                    <van-image :src="imageUrl + processing.useCertificate" width="50px" height="50px" />
                                    <div style="margin-left: 10px;">
                                        <p style="font-weight: bold;">{{ processing.useDestination }}</p>
                                        <p style="font-size: small;;">{{ processing.useTime }}</p>
                                    </div>
                                </div>
                            </van-step>
                        </van-steps>
                    </div>
                    <div v-if="item === '评论'">
                        <div v-for="comment in comments" :key="comment.commentId">
                            <van-divider :style="{ borderColor: 'gray', padding: '0 16px' }" />
                            <div style="display: flex;">
                                <van-image :src="imageUrl + comment.donatorAvatar" width="50px" height="50px" round />
                                <div style="margin-left: 5px;flex: 1;">
                                    <div style="display: flex;">
                                        <div style="flex: 1;">{{ comment.donatorUsername }}</div>
                                        <div style="font-size: small;color: gray;flex: 1;text-align: right;">支持了{{ comment.donationAmount}}元</div>
                                    </div>
                                    <div style="font-size: small;">{{ comment.commentContent }}</div>
                                    <div style="font-size: small;color: gray;">{{ new Date(comment.commentTime).toLocaleString() }}</div>
                                </div>
                            </div>
                        </div>
                        
                    </div>
                </van-tab>
            </van-tabs>
        </div>
        <van-action-bar style="z-index: 1;">
            <van-action-bar-icon icon="share-o" text="分享" @click="goShare" />
            <van-action-bar-button type="primary" :text="time > 0 ? '我要捐款' : '已结束'" @click="goDonate" :disabled="time <= 0" />
        </van-action-bar>
    </div>
    <van-dialog :show="showDialog" title="请输入捐款金额" width="300px" show-cancel-button @confirm="handleSubmit" @cancel="showDialog = false">
        <van-field v-model="donationAmount" type="number" placeholder="请输入捐款金额" clickable @touchstart.stop="showKeyboard = true" />
    </van-dialog>
    /** 分享海报 */
    <van-dialog :show="showShare" :show-confirm-button="false" width="300" style="height: 400px;">
        <!-- 自定义关闭按钮 -->
        <van-icon name="cross" @click="showShare = false" class="share-close-icon" />
        <canvas ref="posterCanvasRef" id="posterCanvas" :width="canvasWidth" :height="canvasHeight" />
    </van-dialog>
    /** 数字键盘 */
    <van-number-keyboard v-model="donationAmount" :show="showKeyboard" @blur="showKeyboard = false" style="z-index: 9999;" />
</template>

<script lang="ts" setup>
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { agencyApi, donatorApi } from '../../api/app';
import { useRouter } from 'vue-router';
import { imageUrl } from '../../api/request';
import { showFailToast, showSuccessToast, showToast } from 'vant';
import QRCode from 'qrcode';

interface IComment {
    commentContent: string;
    commentId: string;
    commentTime: string;
    donatorUsername: string;
    donationAmount: number;
    donatorAvatar: string;
}
interface IProcessing {
    amoutUsed: number;
    useDestination: string;
    useTime: string;
    useCertificate: string;
    donationProcessingId: string;
}

/** 募捐项目id */
const fundraisingProjects = ref({
    agencyId: null,
    expectedFundraisingAmount: 0,
    fundraisingProjectsEndTime: null,
    fundraisingProjectsId: '',
    fundraisingProjectsIntroduction: null,
    fundraisingProjectsName: null,
    fundraisingProjectsPhoto: null,
    fundraisingProjectsStartTime: null,
    fundraisingProjectsType: null,
    totalAmount: 0,
    fundraisingProjectsContent: null,
});
const router = useRouter();
/** 捐赠弹窗 */
const showDialog = ref(false);
const donationAmount = ref();
/** 时间倒计时 */
const time = ref(0);
/** 项目内容标题 */
const titles = ['项目介绍', '项目进展', '评论'];
/** 评论列表 */
const comments = ref<IComment[]>([]);
/** 进展列表 */
const processings = ref<IProcessing[]>([]);
/** 分享弹窗 */
const showShare = ref(false);
const posterCanvasRef = ref(null);
const canvasWidth = 300;
const canvasHeight = 400;
/** 数字键盘 */
const showKeyboard = ref(false);

onMounted(() => {
    const route = useRoute();
    fundraisingProjects.value.fundraisingProjectsId = route.params.fundraisingProjectsId as string;
    // 获取募捐项目信息
    donatorApi.getFundraisingProjectsById({ fundraisingProjectsId: fundraisingProjects.value.fundraisingProjectsId }).then((res: any) => {
        if (res) {
            fundraisingProjects.value = res;
            if (fundraisingProjects.value.fundraisingProjectsEndTime) {
                time.value = new Date(fundraisingProjects.value.fundraisingProjectsEndTime).getTime() - new Date().getTime();
            }
            // 获取募捐项目金额信息
            agencyApi.getFundraisingProjectsAndMoney({
                pageNum: 1,
                pageSize: 10,
                agencyId: fundraisingProjects.value.agencyId,
                fundraisingProjectsId: fundraisingProjects.value.fundraisingProjectsId
            }).then((res: any) => {
                if (res) {
                    fundraisingProjects.value.totalAmount = res.records[0].totalAmount;
                }
            });
        }
    })
    // 获取评论信息
    donatorApi.getCommentByFundraisingProjectsId({ fundraisingProjectsId: fundraisingProjects.value.fundraisingProjectsId }).then((res: any) => {
        if (res) {
            comments.value = res;
        }
    })
    // 获取项目进展
    agencyApi.getDonationProcessingRecords({ fundraisingProjectsId: fundraisingProjects.value.fundraisingProjectsId }).then((res: any) => {
        if (res) {
            processings.value = res.records;
        }
    })
})

/** 返回个人主页 */
const goBack = () => {
    router.back();
}

/** 捐赠 */
const goDonate = () => {
    showDialog.value = true;
}

/** 捐赠提交 */
const handleSubmit = () => {
    const { donatorId } = JSON.parse(localStorage.getItem('donator') || '');
    // 打开支付页面
    const paymentWindow = window.open("http://localhost:8080/alipay/pay?subject=" + fundraisingProjects.value.agencyId + "，" + donatorId + "，" + fundraisingProjects.value.fundraisingProjectsId + "&traceNo=" + Math.floor(Math.random() * 900000) + 100000 + "&totalAmount=" + Number(donationAmount.value),'_blank')
    if (!paymentWindow) {
        showFailToast('无法打开支付界面！');
        return;
    }
    showDialog.value = false;
}

/** 分享 */
const goShare = async () => {
    showShare.value = true;
    // ref 的绑定和 DOM 元素的渲染是异步的，因此需要使用 nextTick 来确保在 DOM 更新之后再尝试访问 ref
    // nextTick 会在下一次 DOM 更新循环结束之后执行回调函数，这样可以确保 ref 已经被正确地绑定。
    await nextTick();
    const canvas = posterCanvasRef.value;
    if (!canvas) return;
    // 创建 2D 画布
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    // 绘制背景矩形大小(矩形左上角坐标x y，宽，高)
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);
    // 绘制图片
    const img = new Image();
    img.src = imageUrl + fundraisingProjects.value.fundraisingProjectsPhoto;
    img.onload = async () => {
        ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
        // 绘制标题
        ctx.font = '24px Arial'; // 文字大小和字体
        ctx.fillStyle = '#000'; // 文字颜色
        ctx.strokeStyle = '#fff'; // 文字描边颜色
        ctx.lineWidth = 4; // 文字描边宽度
        const titleX = (canvasWidth - ctx.measureText(fundraisingProjects.value.fundraisingProjectsName).width) / 2;
        const titleY = canvasHeight / 2;
        ctx.strokeText(fundraisingProjects.value.fundraisingProjectsName, titleX, titleY);
        ctx.fillText(fundraisingProjects.value.fundraisingProjectsName, titleX, titleY);
        // 绘制简介
        ctx.font = '16px Arial';
        const introduceX = (canvasWidth - ctx.measureText(fundraisingProjects.value.fundraisingProjectsIntroduction).width) / 2;
        const introduceY = titleY + 25;
        ctx.strokeText(fundraisingProjects.value.fundraisingProjectsIntroduction, introduceX, introduceY);
        ctx.fillText(fundraisingProjects.value.fundraisingProjectsIntroduction, introduceX, introduceY);
        // 生成并绘制二维码
        const qrCanvas = document.createElement('canvas');
        await QRCode.toCanvas(qrCanvas, 'http://localhost:5173/projectDetail/' + fundraisingProjects.value.fundraisingProjectsId, { width: 120, height: 120 });
        const qrCtx = qrCanvas.getContext('2d');
        if (qrCtx) {
            const qrX = canvasWidth - 60;
            const qrY = canvasHeight - 60;
            ctx.drawImage(qrCanvas, qrX, qrY, 50, 50);
        }
    };
}
</script>

<style lang="less" scoped>
.donation-records, .processing {
    background-color: rgba(237, 231, 231, 0.422);
}
.donation-records {
    width: 100vw;
    height: 100vh;
    padding: 2rem 0 50px 0;
    overflow: auto;

    .donation-records-title {
        background-color: white;

        .title-info {
            padding: 0 10px 10px 10px;

            .title {
                font-size: 1.5rem;
                margin-right: 10px;
            }

            .processing {
                margin-top: 10px;
                padding: 20px;
                display: flex;
                flex-direction: column;
                color: gray;
                
                .processing-top {
                    display: flex;

                    .top-left, .top-right {
                        flex: 1;
                        text-align: center;
                    }
                }
            }

            .processing, .van-count-down {
                font-size: 0.8rem;
            }

            .number, .van-count-down {
                color:#1989FA;
            }
        }
    }
}
.van-field__control {
    border: 1px solid gainsboro;
    border-radius: 5px;
    height: 2rem;
}
.share-close-icon {
    position: absolute;
    top: 10px;
    right: 10px;
    font-size: 1.5rem;
    border-radius: 50%;
    background-color: white;
}
</style>